package com.anabur.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.anabur.persistent.Balance;
import com.anabur.system.AafAbstractDAO;



public class BalanceDAO extends AafAbstractDAO{
	
	public BalanceDAO(SessionFactory sessionFac){
		super(sessionFac);
	}
	
	protected String getNameOfPojo() {
		return Balance.class.getSimpleName();
	}
	
	public List<Balance> getUltimosCincoBalances(String codigoEmpresa, Date fecha) throws Exception{
		List<Balance> list=null;
		Session sess = null;
		try{
			sess = sessionFac.openSession();
			Query query = sess.createQuery("select b from Balance as b " +
					"where b.empresa.codigo = :codigo and b.fechaCierre <= :fecha "+ 
					 "order by b.fechaCierre desc ");
			query.setString("codigo",codigoEmpresa);
			query.setDate("fecha",fecha);
			query.setMaxResults(5);
			list = query.list();
			sess.close();
		}catch (Exception e) {
			sess.close();
			throw e;
		}
		return list;		
	}
	
	public Long getBalanceIDPorFechaYEmpresaID(Date fecha, Long empresaID) throws Exception{
		Long cotizacionID = null;
		Session sess = null;
		try{
			sess = sessionFac.openSession();
			Query query = sess.createQuery("from Balance as b " +
					"where b.fechaCierre = :fechaCierre " +
					"and b.empresa.id = :empresaID") ;
			query.setDate("fechaCierre", fecha);
			query.setLong("empresaID", empresaID);
			Balance b = (Balance) query.uniqueResult();
			if(b != null){
				cotizacionID = b.getID();
			}
			sess.close();
		}catch (Exception e) {
			sess.close();
			throw e;
		}
		return cotizacionID;
	}

	public Balance getUltimoBalance(String codigo) throws Exception {
		List<Balance> list=null;
		Session sess = null;
		try{
			sess = sessionFac.openSession();
			Query query = sess.createQuery("select b from Balance as b " +
					"where b.empresa.codigo = :codigo "+ 
					 "order by b.fechaCierre desc ");
			query.setString("codigo",codigo);
			query.setMaxResults(1);
			list = query.list();
			sess.close();
		}catch (Exception e) {
			sess.close();
			throw e;
		}
		return list.get(0);		
	}
	
}
